package com.controller;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;
@Controller
@RequestMapping("/yunba")
public class YunbaController {
	/**
	 * 云巴推送
	 */
	@RequestMapping(value="/push",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String push() throws Exception {
        String url = "http://rest.yunba.io:8080";	//url地址
        String appkey = "58d9c776691ac9095323544a"; //appkey
        String seckey = "sec-68vmBiSgmaLZ2S9VRe1BkhbvEjfxQ4oesv29ZczUJl5FkKz2"; //Secret Key
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");
        //以JSON格式推送
        String json = "{'method':'publish', 'appkey':'"+appkey+"', 'seckey':'"+seckey+"', 'topic':'topic1'}";
        new JSONObject();
		JSONObject jo = JSONObject.fromObject(json);
        //要推送的消息
        jo.put("msg", "abc");
        StringEntity params = new StringEntity(jo.toString());
        post.setEntity(params);
        HttpResponse response = client.execute(post);
        String result=null;
        if (response.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }
        //打印返回结果
        System.out.println("result:" + result);
        return result.toString();
    }
}
